package com.york.security.security;

import com.york.utils.exception.BusinessException;
import com.york.utils.exception.result.ResponseEnum;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.UUID;


/**
 * @author yangboxiong
 */
@Component
public class JwtUtils {

    //token有效时长
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    //编码秘钥
    private static String tokenSignKey = "eM0$aD6^cA3|aP0^oC0!aN0+cA0&gH";

    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(tokenSignKey);
        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    /**
     * 根据用户名生成token
     *
     * @param userName 用户名
     * @return
     */
    public static String createToken(String userName) {
        String token = Jwts.builder()
                //载荷：默认信息
                .setSubject("SRB-USER")     //令牌主题
                .setIssuedAt(new Date())    //令牌签发时间
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //载荷：自定义信息
                .claim("userName", userName)
                .setId(UUID.randomUUID().toString())    //主要用来作为一次性的token，从而避免重放攻击
                //签名哈希，生成秘钥
                .signWith(SignatureAlgorithm.HS512, getKeyInstance())
                .compressWith(CompressionCodecs.GZIP)
                //组装jwt字符串
                .compact();
        return token;
    }

    public static void main(String[] args) {
        //System.out.println(JwtUtils.createToken("小明"));
    }

    /**
     * 判断token是否有效
     *
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取用户id
     *
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        Claims claims = getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        return userId.longValue();
    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        Claims claims = getClaims(token);
        return (String) claims.get("userName");
    }

    /**
     * 删除 token
     *
     * @param token
     */
    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    /**
     * 校验token并返回Claims
     *
     * @param token
     * @return
     */
    private static Claims getClaims(String token) {
        if (StringUtils.isEmpty(token)) {
            // LOGIN_AUTH_ERROR(-211, "未登录"),
            throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims;
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
        }
    }
}

